package com.ywjh.inter.conn;

import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.ywjh.inter.common.SystemConfig;

public class DBConnection {
	private static DBConnection dbPool;
    private static ComboPooledDataSource dataSource;

    static {
        dbPool = new DBConnection();
    }
    public DBConnection()
    {
        try {

        	String userName = SystemConfig.DATABASE_USERNAME;
    		String password = SystemConfig.DATABASE_PASSWORD;
    		//String driverName = "com.mysql.jdbc.Driver";
    		String driverName="com.mysql.cj.jdbc.Driver";

    		String url = "jdbc:mysql://"+SystemConfig.DATABASE_URL+":3306/"+SystemConfig.DATABASE_NAME+"?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8";
    		System.out.println("url=="+url);
            dataSource = new ComboPooledDataSource();
            dataSource.setUser(userName);
            dataSource.setPassword(password);
            dataSource.setJdbcUrl(url);
            dataSource.setDriverClass(driverName);
            //System.out.println("userName=="+userName);
            //System.out.println("password=="+password);
            // 设置初始连接池的大小！
            dataSource.setInitialPoolSize(2);
            // 设置连接池的最小值！
            dataSource.setMinPoolSize(1);
            // 设置连接池的最大值！
            dataSource.setMaxPoolSize(10);
            // 设置连接池中的最大Statements数量！
            dataSource.setMaxStatements(50);
            // 设置连接池的最大空闲时间！
            dataSource.setMaxIdleTime(60);
        } catch (PropertyVetoException e) {
            throw new RuntimeException(e);
        }
    }

    public final static DBConnection getInstance() {
        return dbPool;
    }

    public static Connection getDBConnection() throws SQLException, ClassNotFoundException
    {
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
        	e.printStackTrace();
            throw new RuntimeException("无法从数据源获取连接 ", e);
        }
    }

    public static DataSource getDataSource() throws SQLException, ClassNotFoundException
    {
    	try {
    		return dataSource;
    	} catch (Exception e) {
    		throw new RuntimeException("无法获取数据源 ", e);
    	}
    }

	public static void close(ResultSet o)
	{
		try
		{
			if (o != null)
				o.close();
		} catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	public static void close(Statement o)
	{
		try
		{
			if (o != null)
				o.close();
		} catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	public static void close(Connection o)
	{
		try
		{
			if (o != null)
				o.close();
		} catch (Exception e)
		{
			e.printStackTrace();
		}
	}
}
